<template>
    <div class="login-form-box only-chxy">
        <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
            <el-form-item prop="user" style="margin-bottom: 35px;">
                <el-input
                    v-model="form.user"
                    prefix-icon="el-icon-user"
                    clearable
                    :placeholder="$t('login.userPlaceholder')"
                    @keyup.enter="login"
                >
                    <!-- <template #append>
					<el-select v-model="userType" style="width: 130px">
						<el-option
							:label="$t('login.admin')"
							value="admin"
						></el-option>
						<el-option
							:label="$t('login.user')"
							value="user"
						></el-option>
					</el-select>
                    </template>-->
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                    v-model="form.password"
                    prefix-icon="el-icon-lock"
                    clearable
                    show-password
                    :placeholder="$t('login.PWPlaceholder')"
                    @keyup.enter="login"
                ></el-input>
            </el-form-item>
            <el-form-item style="margin-top: 20px;margin-bottom: 10px">
                <el-col :span="12">
                    <el-checkbox :label="$t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
                </el-col>
                <el-col :span="12" class="login-forgot">
                    <router-link to="/reset_password">{{ $t("login.forgetPassword") }}？</router-link>
                </el-col>
            </el-form-item>
            <el-form-item>
                <el-button class="login-btn" type="primary" :loading="islogin" round @click="login" >
                    {{ $t("login.signIn")
                    }}
                </el-button>
            </el-form-item>

            <!-- <el-form-item style="margin-top: 25px;margin-bottom: 10px">
                <el-col :span="24">
                    <el-checkbox label v-model="form.agree">
                        我已阅读并同意
                        <span class="color-0080FF cursor-pointer">《用户服务协议》</span>和
                        <span class="color-0080FF cursor-pointer">《隐私协议》</span>
                    </el-checkbox>
                </el-col>
            </el-form-item> -->

            <div class="login-reg">
                {{ $t("login.noAccount") }}
                <router-link to="/user_register">
                    {{
                    $t("login.createAccount")
                    }}
                </router-link>
            </div>
        </el-form>
    </div>

    <sms-code-dialog v-if="dialogSmsCode" ref="smsCodeDialog" @closed="dialogSmsCode = false" @fatherMethod="loginSuccess"></sms-code-dialog>
</template>

<script>
import smsCodeDialog from "./smsCode";
import systemMenu from "@/config/systemMenu";
import publicjs from "@/api/model/publicjs";

export default {
    components: {
        smsCodeDialog,
    },
    data() {
        return {
            // user: "admin",
            // password: "admin",
            // autologin: false,
            //userType: "admin",
            dialogSmsCode: false,
            form: {
                user: "",
                password: "",
                autologin: false,
            },
            rules: {
                user: [
                    {
                        required: true,
                        message: this.$t("login.userError"),
                        trigger: "blur",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: this.$t("login.PWError"),
                        trigger: "blur",
                    },
                ],
            },
            islogin: false,
            userCode: "",
        };
    },
    // watch: {
    //   userType(val) {
    //     if (val == "admin") {
    //       this.form.user = "admin";
    //       this.form.password = "admin";
    //     } else if (val == "user") {
    //       this.form.user = "user";
    //       this.form.password = "user";
    //     }
    //   },
    // },
    mounted() {},
    methods: {
        opSmsLogin(accountId, phone) {
            this.dialogSmsCode = true;
            this.$nextTick(() => {
                this.$refs.smsCodeDialog.setData({
                    accountId: accountId,
                    phone: phone,
                });
                this.$refs.smsCodeDialog.open("Add");
            });
        },
        async login() {
            //aaa
            // eslint-disable-next-line no-debugger
            //debugger
            var validate = await this.$refs.loginForm
                .validate()
                .catch(() => {});
            if (!validate) {
                return false;
            }
            var result = null;
            this.islogin = true;
            //password: this.$TOOL.crypto.MD5(this.form.password),
            //password: this.form.password,
            try {
                var data = {
                    username: this.form.user,
                    password: this.form.password,
                };
                //获取token
                result = await this.$API.auth.token.post(data);
            } catch (e) {
                this.islogin = false;
                return false;
            }
            if (result.status == 200) {
                console.log(result.response);
                if (result.response.isSmsLogin) {
                    this.opSmsLogin(
                        result.response.accountId,
                        result.response.mobile
                    );
                    return;
                }
				this.loginSuccess(result);
                //this.userCode=result.userInfo.userCode;
                // eslint-disable-next-line no-debugger
                //debugger
            } else {
                this.islogin = false;
                this.$message.warning(result.msg);
                return false;
            }

             
            //this.islogin = false;
            // // eslint-disable-next-line no-debugger
            // debugger;
            // console.log(this.userCode);
            // if (this.userCode != "admin") {
            // 	//menu = await this.$API.system.menu.myMenus.get()
            // 	var head = new publicjs.head();
            // 	publicjs.initHead(head, "getMenu");
            // 	var ed = new publicjs.entitydata(head);
            // 	var eo = { UserCode: this.userCode };
            // 	ed.Data.Content.ObjectList.Object.push(eo);
            // 	try {
            // 		var returnValueStr = await this.$API.auth.objProcess.post(
            // 			ed
            // 		);
            // 		//console.log(returnValueStr);
            // 		let returnValue = JSON.parse(returnValueStr);
            // 		if (returnValue.Result.OpFlag == "1") {
            // 			//let purview = returnValue.Result.Content.split(",")
            // 			let purview = returnValue.Result.Content;
            // 			let newmenu = JSON.parse(
            // 				JSON.stringify(systemMenu.allMunu)
            // 			);
            // 			this.getDataByType(purview, newmenu.menu);
            // 			// eslint-disable-next-line no-debugger
            // 			//debugger;
            // 			mymenu.menu = this.deepClone(newmenu.menu);
            // 		} else {
            // 			this.$message.error(
            // 				"操作失败:" + returnValue.Result.OpMsg
            // 			);
            // 		}
            // 	} catch (error) {
            // 		this.loading = false;
            // 		this.$alert(error.message, "提示", { type: "error" });
            // 		return false;
            // 	}
            // }
        },
        loginSuccess(result) {
			console.log("菜单",result)
            this.$TOOL.cookie.set("TOKEN", result.response.token.token, {
                expires: this.form.autologin ? 24 * 60 * 60 : 0,
            });
            this.$TOOL.data.set("USER_INFO", {
                AccountId: result.response.accountId,
                AccountType: result.response.accountType,
                AccountTypeDesc: result.response.accountTypeDesc,
                Code: result.response.code,
                Name: result.response.name,
                OrgId: result.response.orgId,
                OrgCode: result.response.orgCode,
                OrgName: result.response.orgName,
				Mobile:result.response.mobile
            });

            if (result.response.menus == 0) {
                this.islogin = false;
                this.$alert(
                    "当前用户无任何菜单权限，请联系系统管理员",
                    "无权限访问",
                    {
                        type: "error",
                        center: true,
                    }
                );
                return false;
            }
            //var mymenu = systemMenu.allMunu;
            //console.log("menu",mymenu.menu);
            //this.$TOOL.data.set("MENU", mymenu.menu);

            this.$TOOL.data.set("MENU", result.response.menus);

            this.$router.replace({
                path: "/",
            });
            this.$message.success("Login Success 登录成功");
            this.islogin = false;
        },

        getDataByType(purviewList, data) {
            // eslint-disable-next-line no-debugger
            //debugger;
            for (let i = data.length - 1; i >= 0; i--) {
                if (data[i].pid) {
                    if (purviewList.indexOf("," + data[i].pid + ",") < 0) {
                        //delete data[i];
                        data.splice(i, 1);
                    } else {
                        if (data[i].children && data[i].children.length > 0)
                            this.getDataByType(purviewList, data[i].children);
                    }
                } else {
                    data.splice(i, 1);
                }
            }
        },
        deepClone(source) {
            // eslint-disable-next-line no-debugger
            //debugger;
            if (!source || typeof source !== "object" || source == null) {
                return source;
            }
            const target = Array.isArray(source) ? [] : {};
            for (const key in source) {
                if (source[key]) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                        if (
                            typeof source[key] === "object" &&
                            source[key] !== null
                        ) {
                            target[key] = this.deepClone(source[key]);
                        } else {
                            target[key] = source[key];
                        }
                    }
                }
            }
            return target;
        },
    },
};
</script>

<style scoped>
.login-form-box:deep(.el-input__wrapper) {
    /* border-radius: 8px; */
    border-radius: 0.416vw;
    border: 0.052vw solid #999999;
    /* background: rgba(230, 250, 255); */
    font-family: PingFang SC;
    font-weight: 500;
    /* font-size: 24px; */
    font-size: 1.25vw;
    color: #212121;
}

.login-form-box:deep(.el-input) {
    /* height: 150%; */
    /* height: 80px */
    /* height: 7.407vh; */
    /* height: 60px */
    height: 5.556vh;
}

.login-form-box:deep(.el-input__password) {
    /* font-size: 24px !important; */
    font-size: 1.25vw !important;
}

/* .login-form-box:deep(.el-checkbox__inner) {
	width: 20px;
	height: 20px;
} */

.login-form-box:deep(.el-checkbox__label) {
    /* font-size: 16px; */
    font-size: 0.833vw;
}

.login-btn {
    width: 100%;
    height: 120%;
    font-family: PingFang SC;
    font-weight: 500;
    /* font-size: 20px; */
    font-size: 1.041vw;
    color: #ffffff;
    background: #0080ff;
    border-radius: 30px;
}

.color-0080FF {
    color: #0080ff;
}
.cursor-pointer {
    cursor: pointer;
}

.el-form-item {
    margin-bottom: 20px !important;
}
</style>
